package com.newshub.ai.service.impl;

import com.newshub.ai.model.dto.ChatRequest;
import com.newshub.ai.service.ChatBISessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ChatBI 会话管理服务实现类
 * 负责存储和管理对话历史记录
 */
@Slf4j
@Service
public class ChatBISessionServiceImpl implements ChatBISessionService {
    
    /**
     * 会话存储：sessionId -> 消息历史
     */
    private final Map<String, List<ChatRequest.ChatMessage>> sessions = new ConcurrentHashMap<>();
    
    /**
     * 会话时间戳：sessionId -> 最后活跃时间
     */
    private final Map<String, Long> sessionTimestamps = new ConcurrentHashMap<>();
    
    /**
     * 会话超时时间：30分钟
     */
    private static final long SESSION_TIMEOUT = 30 * 60 * 1000;
    
    @Override
    public void addMessage(String sessionId, ChatRequest.ChatMessage message) {
        if (sessionId == null || message == null) {
            log.warn("SessionId 或 Message 为空，跳过添加");
            return;
        }
        
        cleanupExpiredSessions();
        
        sessions.computeIfAbsent(sessionId, k -> new ArrayList<>()).add(message);
        sessionTimestamps.put(sessionId, System.currentTimeMillis());
        
        log.debug("添加消息到会话 {}: role={}, content={}", 
            sessionId, message.getRole(), 
            message.getContent() != null ? message.getContent().substring(0, Math.min(50, message.getContent().length())) + "..." : "null");
    }
    
    @Override
    public List<ChatRequest.ChatMessage> getHistory(String sessionId) {
        if (sessionId == null) {
            log.warn("SessionId 为空，返回空历史");
            return new ArrayList<>();
        }
        
        cleanupExpiredSessions();
        
        List<ChatRequest.ChatMessage> history = sessions.getOrDefault(sessionId, new ArrayList<>());
        log.debug("获取会话 {} 历史，共 {} 条消息", sessionId, history.size());
        
        return history;
    }
    
    @Override
    public void clearSession(String sessionId) {
        if (sessionId == null) {
            return;
        }
        
        sessions.remove(sessionId);
        sessionTimestamps.remove(sessionId);
        log.info("清空会话: {}", sessionId);
    }
    
    @Override
    public boolean hasSession(String sessionId) {
        if (sessionId == null) {
            return false;
        }
        
        cleanupExpiredSessions();
        return sessions.containsKey(sessionId);
    }
    
    @Override
    public Map<String, Object> getSessionStats() {
        cleanupExpiredSessions();
        
        return Map.of(
            "activeSessions", sessions.size(),
            "totalMessages", sessions.values().stream().mapToInt(List::size).sum(),
            "maxSessionTimeout", SESSION_TIMEOUT / 1000 / 60 + " 分钟"
        );
    }
    
    /**
     * 清理过期会话
     */
    private void cleanupExpiredSessions() {
        long now = System.currentTimeMillis();
        
        // 清理过期的会话时间戳
        sessionTimestamps.entrySet().removeIf(entry -> {
            boolean expired = now - entry.getValue() > SESSION_TIMEOUT;
            if (expired) {
                log.debug("会话 {} 已过期，准备清理", entry.getKey());
            }
            return expired;
        });
        
        // 清理对应的会话数据
        sessions.keySet().removeIf(key -> !sessionTimestamps.containsKey(key));
        
        // 如果清理了会话，记录日志
        if (sessions.size() < sessionTimestamps.size()) {
            log.info("清理了 {} 个过期会话", sessionTimestamps.size() - sessions.size());
        }
    }
}
